import React, { useState, useEffect } from 'react';
import { Tabs, Card, Loading, Empty, DotLoading } from 'antd-mobile';
import axiosInstance from '../axiosInstance';

// 样式对象集中定义
const styles = {
  container: {
    padding: '12px',
    minHeight: '100%',
    background: '#f5f5f5',
    width: '100%',
    boxSizing: 'border-box',
    overflowX: 'hidden'
  },
  title: {
    margin: '0 0 16px',
    fontSize: '16px',
    color: '#333'
  },
  tabs: {
    '--title-font-size': '15px',
    '--active-title-color': '#1677ff',
    '--active-line-color': '#1677ff',
    '--content-padding': '0',
    background: '#fff',
    borderRadius: '8px',
    padding: '12px 12px 0'
  },
  loading: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    padding: '40px 0',
    color: '#666',
    fontSize: '15px'
  },
  empty: {
    padding: '40px 0',
    fontSize: '15px',
    color: '#666'
  },
  card: {
    margin: '12px 0',
    background: '#fff',
    borderRadius: '8px',
    boxShadow: '0 1px 2px rgba(0,0,0,0.05)'
  },
  cardContent: {
    padding: '12px',
    color: '#333'
  },
  sectionTitle: {
    fontSize: '16px',
    fontWeight: 600,
    margin: '20px 0 12px',
    color: '#333'
  },
  bullet: {
    padding: '8px 0 8px 24px',
    position: 'relative',
    lineHeight: 1.6,
    fontSize: '15px'
  },
  bulletDot: {
    position: 'absolute',
    left: '8px',
    color: '#666'
  },
  normalLine: {
    padding: '8px 0',
    fontSize: '15px',
    lineHeight: 1.6
  }
};

function AnalysisPage() {
  const [activeKey, setActiveKey] = useState('topics');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({
    topics: '',
    timeline: '',
    growth: '',
    emotion: ''
  });

  const formatText = (text) => {
    if (!text || text.length < 1) return null;
    return text.split('\n').map((line, index) => {
      if (line.startsWith('【') && line.endsWith('】')) {
        return (
          <div key={index} style={styles.sectionTitle}>
            {line.slice(1, -1)}
          </div>
        );
      } else if (line.startsWith('-')) {
        return (
          <div key={index} style={styles.bullet}>
            <span style={styles.bulletDot}>•</span>
            {line.slice(1).trim()}
          </div>
        );
      } else if (line.trim()) {
        return (
          <div key={index} style={styles.normalLine}>
            {line}
          </div>
        );
      }
      return null;
    });
  };

  const fetchData = async (type) => {
    setLoading(true);
    try {
      const res = await axiosInstance.get(`/analysis/${type}`);
      setData(prev => ({
        ...prev,
        [type]: res.data?.[type] || ''
      }));
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(activeKey);
  }, [activeKey]);

  const renderContent = (type) => {
    if (loading) {
      return (
        <div style={styles.loading}>
          <span style={{ marginRight: 8 }}>加载中</span>
          <DotLoading />
        </div>
      );
    }

    if (!data[type]) {
      return (
        <Empty
          description="暂无数据"
          style={styles.empty}
        />
      );
    }

    return (
      <Card style={styles.card}>
        <div style={styles.cardContent}>
          {formatText(data[type])}
        </div>
      </Card>
    );
  };

  return (
    <div style={styles.container}>
      <h4 style={styles.title}>日记整理</h4>

      <Tabs
        activeKey={activeKey}
        onChange={setActiveKey}
        style={styles.tabs}
      >
        <Tabs.Tab title='主题分析' key='topics'>
          {renderContent('topics')}
        </Tabs.Tab>
        <Tabs.Tab title='时间线' key='timeline'>
          {renderContent('timeline')}
        </Tabs.Tab>
        <Tabs.Tab title='成长记录' key='growth'>
          {renderContent('growth')}
        </Tabs.Tab>
        <Tabs.Tab title='情感分析' key='emotion'>
          {renderContent('emotion')}
        </Tabs.Tab>
      </Tabs>
    </div>
  );
}

export default AnalysisPage;